package user

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"weekly-exam-3/config"
	"weekly-exam-3/internal/model/dao"
	"weekly-exam-3/tools"
)

type Logins struct {
	Mobile string `form:"mobile" json:"mobile" xml:"mobile"  binding:"required"`
	Code   string `form:"code" json:"code" xml:"code"  binding:"required"`
}

func Login(c *gin.Context) {
	var json Logins
	if err := c.ShouldBindJSON(&json); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	//get := config.Rdb.Get("sendSms")
	//if get.Val() != json.Code {
	//	c.JSON(http.StatusBadRequest, gin.H{
	//		"message": "验证码不正确",
	//	})
	//	return
	//}
	var user dao.User
	config.DB.Where("mobile=?", json.Mobile).Limit(1).Find(&user)
	if user.ID == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    500,
			"message": "没有该用户",
		})
		return
	}
	if len(json.Mobile) != 11 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    500,
			"message": "手机号格式不正确",
		})
		return
	}
	jwtSign := tools.NewJWT("2208a")
	//生成token
	jwtClaims := tools.CustomClaims{
		ID: int64(user.ID),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 86400,
		},
	}
	token, err := jwtSign.CreateToken(jwtClaims)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "token生成失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"message": "登录成功",
		"data":    token,
	})
}
